package web.dao;

import web.dao.Criteria.SqlOperator;

/**
 * 
 * @author orlin
 */
public class OrderBy extends QueryPatternImpl {

	protected String fieldName;
	private SqlOperator order;

	public static OrderBy ascending(String fieldName) {
		return new OrderBy(fieldName, SqlOperator.ASC);
	}

	public static OrderBy descending(String fieldName) {
		return new OrderBy(fieldName, SqlOperator.DESC);
	}

	protected OrderBy(String fieldName, SqlOperator order) {
		super();
		this.fieldName = fieldName;
		if (!SqlOperator.DESC.equals(order)) {
			/** if it is not DESC, then should be ASC */
			order = SqlOperator.ASC;
		}
		this.order = order;
	}

	public String getFieldName() {
		return fieldName;
	}

	public void setFieldName(String fieldName) {
		this.fieldName = fieldName;
	}

	@Override
	public String getOrderByClause() {
		StringBuffer result = new StringBuffer(); 
		result.append(getParentQuery().getNickName());
		result.append(DOT);
		result.append(getFieldName());
		switch (order) {
			case ASC:
				result.append(ASC);
				break;
			case DESC:
				result.append(DESC);
				break;
			default:
				throw new RuntimeException("unknown sql operator");
		}
		String orderByClause = super.getOrderByClause();
		if ((null != orderByClause) && (!orderByClause.isEmpty())) {
			result.append(COMMA);
			result.append(orderByClause);
		}
		return result.toString();
	}
}
